package com.pinhuba.bams.framework.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;

import org.apache.http.client.methods.HttpGet;

import com.pinhuba.bams.framework.exception.NetworkException;
import com.pinhuba.bams.framework.exception.TimeoutException;
import com.pinhuba.bams.framework.util.Loger;

public class HttpGetUtil {

	/**
	 * execute request
	 * 
	 * @param httpGetUrl
	 * @return
	 * @throws TimeoutException
	 * @throws NetworkException
	 */
	private static String executeRequest(String httpGetUrl)
			throws TimeoutException, NetworkException, IOException {
		Loger.d("HttpGetURL = " + httpGetUrl);
		HttpGet httpGet = new HttpGet(httpGetUrl);
		return BaseHttp.sendRequest(httpGet);
	}

	/**
	 * execute request
	 * 
	 * @param url
	 * @param hmParams
	 * @return
	 * @throws TimeoutException
	 * @throws NetworkException
	 */
	public static String executeRequest(String url,
			HashMap<String, String> hmParams) throws TimeoutException,
			NetworkException, IOException {
		StringBuffer sb = new StringBuffer();
		sb.append(url).append("?");
		Iterator<Entry<String, String>> iter = hmParams.entrySet().iterator();
		boolean isFirstParam = true;
		while (iter.hasNext()) {
			if (!isFirstParam) {
				sb.append("&");
			} else {
				isFirstParam = false;
			}
			Entry<String, String> entry = iter.next();
			try {
				sb.append(URLEncoder.encode(entry.getKey(), BaseHttp.ENCODING));

				sb.append("=");
				String value = entry.getValue();
				if (value == null) {
					value = "";
					Loger.e("Key - value is null ------" + entry.getKey());
				}
				sb.append(URLEncoder.encode(value, BaseHttp.ENCODING));

			} catch (UnsupportedEncodingException e) {
				throw new NetworkException(e);
			}

		}
		// Loger.d("拼接出来的sb:"+sb.toString());
		return executeRequest(sb.toString());
	}

}
